package com.alameda.common.commonpent.commonback.impl;

import com.alameda.common.annotation.UnLogicDeleteIntercept;
import com.alameda.common.base.bo.CommonBackBO;
import com.alameda.common.base.dto.CommonDTO;
import com.alameda.common.base.enums.CommonTableEnum;
import com.alameda.common.commonpent.commonback.api.CommonBackTemplate;
import com.alameda.common.commonpent.commonback.business.CommonBackCommonpent;
import com.alameda.common.utils.ObjectUtils;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 通用后端 门面层
 *
 * @author Lv
 * @date 2024/2/19
 */
@SuppressWarnings("all")
@Component
public class CommonBackTemplateImpl<T> implements CommonBackTemplate<T> {

    @Resource
    private CommonBackCommonpent<T> commonBackCommonpent;

    /**
     * 通用获取详情
     *
     * @param commonDTO 通用后端信息
     * @return
     */
    @Override
    public T get(CommonDTO commonDTO) {
        // 数据模型转换
        CommonBackBO commonBackBO = convertToBO(commonDTO);
        Map<String, Object> map = commonBackCommonpent.get(commonBackBO);
        return convertData(map, commonBackBO);
    }

    /**
     * 通用逻辑删除
     *
     * @param commonDTO 通用后端信息
     * @return
     */
    @Override
    public T remove(CommonDTO commonDTO) {
        // 数据模型转换
        CommonBackBO commonBackBO = convertToBO(commonDTO);
        return (T) commonBackCommonpent.remove(commonBackBO);
    }

    /**
     * 执行查询sql操作 无逻辑删除拦截处理
     *
     * @param sql 查询语句
     * @return
     */
    @UnLogicDeleteIntercept
    @Override
    public List<HashMap> executeFind(String sql) {
        return commonBackCommonpent.executeFind(sql);
    }

    /**
     * 执行删除sql操作 物理删除
     *
     * @param sql 删除语句
     * @return
     */
    @Override
    public Integer executeDelete(String sql) {
        return commonBackCommonpent.executeDelete(sql);
    }

    /**
     * 详情数据模型转换 （方便前端显示）
     *
     * @param mapData      数据
     * @param commonBackBO 通用后端业务对象
     * @return
     */
    private T convertData(Map<String, Object> mapData, CommonBackBO commonBackBO) {
        // 获取类名称
        String className = commonBackCommonpent.getClassName(commonBackBO.getTableEnum().name().toLowerCase());
        // 获取类字节码
        Class<?> targetObjectClass = commonBackCommonpent.getTargetObjectClass(commonBackBO.getTableEnum().getPojoPath(), className);
        // 数据模型转换 下划线转换为驼峰
        Object data = mapData.get("data");

        T t = null;
        try {
            t = (T) ObjectUtils.convert(data, targetObjectClass);
        } catch (Exception e) {
            t = convert(data, targetObjectClass);
        }

        return t;
    }

    /**
     * 扩展字段sql列名称
     */
    private final static String EXT_DATA_CLOUMN = "ext_data";

    /**
     * 扩展字段对象名称
     */
    private final static String EXT_DATA_NAME = "extData";

    /**
     * 转换处理扩展字段不为空场景
     *
     * @param data              数据
     * @param targetObjectClass 目标对象
     * @return
     */
    private T convert(Object data, Class<?> targetObjectClass) {
        String json = JSONObject.toJSONString(data);
        Map map = JSONObject.parseObject(json, Map.class);

        Object extData = map.get(EXT_DATA_CLOUMN);
        // 移除扩展字段 防止整体转换报错
        map.remove(EXT_DATA_CLOUMN);

        // 获取扩展字段内容
        Map extMap = ObjectUtils.convert(extData, Map.class);

        // 转换处理目标对象
        String jsonString = JSONObject.toJSONString(map);
        T targetObject = (T) JSONObject.parseObject(jsonString, targetObjectClass);

        // 反射字节码获取字段信息
        Field[] fields = getAllFields(targetObject);

        // 通过反射将扩展字段疯转进目标对象
        for (int i = fields.length - 1; i >= 0; i--) {
            Field field = fields[i];
            if (EXT_DATA_NAME.equals(field.getName())) {
                try {
                    field.setAccessible(Boolean.TRUE);
                    field.set(targetObject, extMap);
                    field.setAccessible(Boolean.FALSE);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                // 封装数据后立刻跳出循环
                break;
            }
        }

        return targetObject;
    }

    /**
     * 获取模板对象字段信息
     *
     * @param convert 模板对象
     * @return
     */
    private Field[] getAllFields(T convert) {
        Class<?> aClass = convert.getClass();
        return aClass.getDeclaredFields();
    }

    /**
     * 数据模型转换
     *
     * @param commonDTO 通用后端信息
     * @return
     */
    private CommonBackBO convertToBO(CommonDTO commonDTO) {
        return CommonBackBO.builder()
                .id(commonDTO.getId())
                .idList(commonDTO.getIdList())
                .tableEnum(CommonTableEnum.valueOf(commonDTO.getTableName().toUpperCase()))
                .build();
    }
}
